package com.example.musicplayer

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.database.Cursor
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import androidx.core.app.NotificationCompat

class MusicService : Service() {

    companion object{
        const val Command = "Operate"
    }

    val CHANNEL_ID = "My Channel"
    val NOTIFICATION_ID = 1

    val tag = "MusicService"
    val mediaPlayer = MediaPlayer()
    val musicList: MutableList<String> = mutableListOf()
    val musicNameList: MutableList<String> = mutableListOf()
    var currentMusic = 0
    var isPaused = false
    val binder = MusicBinder()

    inner class MusicBinder: Binder() {
        val musicName
            get() = musicNameList[currentMusic]

        var currentPosition
            get() = mediaPlayer.currentPosition
            set(value) = mediaPlayer.seekTo(value)

        val duration
            get() = mediaPlayer.duration

        val size
            get() = musicList.size

        val currentIndex
            get() = currentMusic

        val musicImage
            get() = musicImageList[currentMusic]
    }

    val musicImageList: MutableList<Int> = mutableListOf(
        R.drawable.img1,
        R.drawable.img2,
        R.drawable.img3,
        R.drawable.img4,
        R.drawable.img5,
        R.drawable.img6
    )

    override fun onCreate() {
        super.onCreate()
        getMusicList()
        mediaPlayer.setOnPreparedListener {
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            currentMusic++
            if (currentMusic >= musicList.size) currentMusic = 0
            play()
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Command,1)
        when(operate){
            1 -> play()
            2 -> pause()
            3 -> stop()
            4 -> next()
            5 -> prev()
        }

        return super.onStartCommand(intent, flags, startId)
    }
    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    fun play() {
        if (musicList.size == 0) return
        val path = musicList[currentMusic]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()

        } catch (e: Exception){
            Log.d(tag, "onPlay: ${e.message}")
        }
        sendNotification()
    }

    fun pause() {
        if (isPaused) {
            mediaPlayer.start()
            isPaused = false
        } else {
            mediaPlayer.pause()
            isPaused = true
        }

    }

    fun stop() {
        mediaPlayer.stop()
        stopSelf()
    }

    fun next() {
        currentMusic++
        if (currentMusic >= musicList.size) currentMusic = 0
        play()
    }

    fun prev() {
        currentMusic--
        if (currentMusic < 0) currentMusic = musicList.size - 1
        play()
    }

    @SuppressLint("Range")
    private fun getMusicList(){
        val cursor: Cursor? = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            null
        )
        if (cursor != null){
            while (cursor.moveToNext()){
                val path: String = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                val name: String = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
                musicList.add(path)
                musicNameList.add(name)
            }
            cursor.close()
        }
    }

    private fun sendNotification() {
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val builder: NotificationCompat.Builder

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(CHANNEL_ID, "Test Channel", NotificationManager.IMPORTANCE_LOW)
            notificationManager.createNotificationChannel(notificationChannel)
            builder = NotificationCompat.Builder(this, CHANNEL_ID)
        } else {
            builder = NotificationCompat.Builder(this)
        }

        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE)

        val notification = builder.setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle(musicNameList[currentMusic])
            .setContentText("music")
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        notificationManager.notify(NOTIFICATION_ID, notification)
    }
}